<?php
namespace app\admin\controller;
use \think\Controller;
use \think\Db;
// use app\admin\validate\Video;
class Video extends BaseController
{
public function index(){
		//调用模型层，实现获取用户列表数据的功能
		//$videos=Db::name("videos")->select();

		$videos=Db::query('select * from videos v,videotype t where v.tid=t.tid order by v.vid desc');
		$this->assign("videos",$videos);
		$t=Db::name("videotype")->select();
		$this->assign('types',$t);
        return $this->fetch();

		
	}
	public function delete($id){
		// 先删除头像：find方法和unlink
		$d_user=Db::name("videos")->find($id);
		if($d_user)
		{
			if(file_exists("../public/static/posters/".$d_user["pic"])){
			unlink("../public/static/posters/".$d_user["pic"]);
		if(Db::name("videos")->delete($id))
	{
		$this->success('删除成功');
	}else {$this->error('删除失败');}}
	else{
		if(Db::name("videos")->delete($id))
	{
		
		$this->success('删除成功');
	}else $this->error('没有海报,删除失败');
	}
}
	}
	public function add(){
		$info="";
		$file = request()->file('pic');	
		// dump($file);
		if($file){
        $info = $file->rule('uniqid')->validate(['size'=>3000000,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'static'.DS.'posters');
    }
    // dump ($info);
    
    if(request()->isPost()){
    	//创建数组,给video表的所有字段赋值
    	//自增长字段不用赋值,有默认值的不用赋值,允许为空的也可以不赋值
    	

    $data=[
			'videoname'=>input('param.videoname'),
			'tid'=>input('param.videotype'),
			'pic'=>empty($info)?'default.jpg':$info->getFilename(),
			'intro'=>input('param.videointro'),
			'uploaddate'=>date('Y-m-d'),
			'uploadadmin'=>2,
			'downtimes'=>0,
			'hittimes'=>0,
			'address'=>input('param.address')
		];

		$validate = \think\Loader::validate('Video');
		if(!$validate->check($data)){
			$this->error($validate->getError());
		}


		if(Db::name("videos")->insert($data)){
			$this->success("添加视频成功");
		}else{
			$this->error("添加视频失败");
		}

    }
	}
	public function edit()
	{
		# code...
		$vid=input("param.vid");
		$type=Db::name("videos")->find($vid);
		echo json_encode($type);
	}
	public function update()
	{
		# code...
		$vid=input("param.vid");
		$info="";
		$file = request()->file('pic');	
		// dump($file);
		if($file){
			$d_user=Db::name("videos")->find($vid);
		if($d_user)
		{
			if(file_exists("../public/static/posters/".$d_user["pic"])){
			unlink("../public/static/posters/".$d_user["pic"]);}
        $info = $file->rule('uniqid')->validate(['size'=>3000000,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'static'.DS.'posters');
    }
    if(request()->isPost()){
		
		$data=[
			'vid'=>$vid,
			'videoname'=>input('param.videoname'),
			'tid'=>input('param.videotype'),
			'pic'=>empty($info)?'default.jpg':$info->getFilename(),
			'intro'=>input('param.videointro'),
			'uploaddate'=>date('Y-m-d'),
			'uploadadmin'=>2,
			'downtimes'=>0,
			'hittimes'=>0,
			'address'=>input('param.address')
		];
		if(Db::name("videos")->update($data)){
			$this->success("修改成功");
		}else{
			$this->error("修改失败");
		}
	}
	}
}
}
